﻿using Lgc_VoteSys.Models.Database;
using Lgc_VoteSys.Models.DataUploading;
using Lgc_VoteSys.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Security.Claims;

namespace Lgc_VoteSys.Controllers
{
    /// <summary>
    /// 资料上传模块
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DataUploadingController : ControllerBase
    {
        // 定义数据库上下文
        private readonly Lgc_VoteSysContext _db;
        private readonly IJWTService _jwtService;

        /// <summary>
        /// 构造方法 构造注入
        /// 把数据库上下文初始化
        /// </summary>
        /// <param name="db"></param>
        public DataUploadingController(Lgc_VoteSysContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }

        /// <summary>
        /// 资料上传-列表页
        /// </summary>
        /// <param name="list">输入类别(工程、技术、产品)</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]//标签 接口需要授权
        public string Check(DataUploading_Check list)
        {
            //获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
            var userEmail = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; // 获取登录用户的手机号
            
            // 获取用户的类型 0为普通用户 1为企业用户
            var userType = _db.Users.Where(x => x.UEmail == userEmail).Select(x => x.UType).FirstOrDefault();
            if (userType == 0)
            {
                return "普通用户不能上传资料";
            }

            if (string.IsNullOrEmpty(list.DataUploadingName))
            {
                return "请填写类别";
            }
            if (list.DataUploadingName != "工程" && list.DataUploadingName != "技术" && list.DataUploadingName != "产品")
            {
                return "请检查类别名称";
            }
            //var check = _db.Audits.Count(x => x.UEmail == userEmail && x.PvcName == list.DataUploadingName);
            var check = _db.EnterpriseDetails.Count(x => x.UEmail == userEmail && x.PvcName == list.DataUploadingName);
            if (check > 0)
            {
                return "是";
            }
            else
            {
                return "否";
            }
        }

        /// <summary>
        /// 资料上传接口
        /// </summary>
        /// <param name="item">获奖类型：1最佳奖 2优秀奖</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]//标签 接口需要授权
        public string DataUp_add(DataUploading_DataUp_add item)
        {
            //获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
            var userEmail = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; // 获取登录用户的手机号

            // 获取用户的类型 0为普通用户 1为企业用户
            var userType = _db.Users.Where(x => x.UEmail == userEmail).Select(x => x.UType).FirstOrDefault();
            if (userType == 0)
            {
                return "普通用户不能上传资料";
            }

            if (item.PVC_name != "工程" && item.PVC_name != "技术" && item.PVC_name != "产品")
            {
                return "请检查类别名称";
            }

            // 读取用户有木有上传过该类型的资料
            var check = _db.EnterpriseDetails.Count(x => x.UEmail == userEmail && x.PvcName == item.PVC_name);
            if (check > 0)
            {
                return "您已上传过该类型的资料";
            }

            // 获取当前时间戳
            DateTimeOffset dateTimeOffset = DateTimeOffset.UtcNow;
            long unixTimeMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();
            string timestamp = unixTimeMilliseconds.ToString();

            foreach (var award in item.Award)
            {
                // 输入数据库图片字段
                var pic = "";

                if (string.IsNullOrEmpty(item.PVC_name) || string.IsNullOrEmpty(item.ED_logo) || string.IsNullOrEmpty(item.ED_name) || string.IsNullOrEmpty(item.ED_profile) || award.ED_time == null)
                {
                    return "内容不能为空";
                }
                if(award.ED_type != 1 && award.ED_type != 2)
                {
                    return "请检查获奖类型 1最佳奖 2优秀奖";
                }
                if (string.IsNullOrEmpty(award.Picture.ED_pic1) && string.IsNullOrEmpty(award.Picture.ED_pic2) && string.IsNullOrEmpty(award.Picture.ED_pic3) && string.IsNullOrEmpty(award.Picture.ED_pic4) && string.IsNullOrEmpty(award.Picture.ED_pic5))
                {
                    return "图片不能为空";
                }

                if (!string.IsNullOrEmpty(award.Picture.ED_pic1))
                {
                    pic += award.Picture.ED_pic1 + ",";
                }
                if (!string.IsNullOrEmpty(award.Picture.ED_pic2))
                {
                    pic += award.Picture.ED_pic2 + ",";
                }
                if (!string.IsNullOrEmpty(award.Picture.ED_pic3))
                {
                    pic += award.Picture.ED_pic3 + ",";
                }
                if (!string.IsNullOrEmpty(award.Picture.ED_pic4))
                {
                    pic += award.Picture.ED_pic4 + ",";
                }
                if (!string.IsNullOrEmpty(award.Picture.ED_pic5))
                {
                    pic += award.Picture.ED_pic5 + ",";
                }
                // 去掉最后一个逗号
                pic = pic.Substring(0, pic.Length - 1);

                _db.EnterpriseDetails.Add(new EnterpriseDetail
                {
                    EdId = timestamp,
                    UEmail = userEmail,
                    PvcName = item.PVC_name,
                    EdLogo = item.ED_logo,
                    EdName = item.ED_name,
                    EdProfile = item.ED_profile,
                    EdTime = award.ED_time,
                    EdType = award.ED_type,
                    EdPicture = pic,
                    EdState = 0
                });
            }
            return _db.SaveChanges() > 0 ? "上传成功" : "上传失败";
        }

        /// <summary>
        /// 审核资料接口
        /// </summary>
        /// <param name="data">依次输入项目编号、审核结果(1通过、-1拒绝)</param>
        /// <returns></returns>
        [HttpPost]
        public string Audit(DataUploading_Audit data)
        {
            var audit = _db.EnterpriseDetails.Count(x => x.EdId == data.id);
            if (audit <= 0)
            {
                return "请检查项目编号";
            }
            if (data.result == 0)
            {
                return "请填写审核结果";
            }
            if (data.result != -1 && data.result != 1)
            {
                return "请检查审核结果 1通过 2驳回";
            }
            var state = _db.EnterpriseDetails.FirstOrDefault(x => x.EdId == data.id);
            if (state.EdState < 0)
            {
                return "该项目此前审核结果为：拒绝";
            }
            if (state.EdState > 0)
            {
                return "该项目此前审核结果为：通过";
            }
            var award = _db.EnterpriseDetails.Where(x => x.EdId == data.id).ToList();
            foreach (var item in award)
            {
                if (data.result == -1)
                {
                    item.EdState = -1;
                    continue;
                }else if (data.result == 1)
                {
                    item.EdState = 1;
                }
            }
            return _db.SaveChanges() > 0 ? "审核成功" : "审核失败";
        }
    }
}
